//
//  CWCCustomViewController.m
//  ChuanNews
//
//  Created by dllo on 16/4/21.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CWCCustomViewController.h"
#import "CostomCell.h"
#import "BaseHeader.h"
#import "CWCImageCell.h"
#import "UIImageView+WebCache.h"
#import "CWCNewsDetailViewController.h"
#import "CWCPhotoDetailViewController.h"
#define HHHHH self.scrollView.frame.size.height
@interface CWCCustomViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property(nonatomic, retain)MBProgressHUD *hud;
@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, retain)UIPageControl *pageControl;
@property(nonatomic, retain)UIView *headView;

@property(nonatomic, assign)NSInteger page;
@property(nonatomic, assign)BOOL isUpLoading;


@property(nonatomic, retain)NSMutableArray *btArray;
@end

@implementation CWCCustomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.array = [NSMutableArray array];
    self.headArray = [NSMutableArray array];
    //加载菊花
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"loading......";
    self.hud.detailsLabelText = @"网络正在加载,请稍后......";
    self.hud.color = [UIColor blackColor];
    self.hud.dimBackground = YES;
    self.page = 0;
    [self creatDataWith:self.page];
    
    self.isUpLoading = NO;
    [self addFooter];
    [self addHeader];
    
}
- (void)addHeader{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isUpLoading = NO;
        self.page = 0;
        [self creatDataWith:self.page];
        
    }];
}

- (void)addFooter {
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        self.isUpLoading = YES;
        self.page += 20;
        [self creatDataWith:self.page];
        
    }];
}
#pragma mark - 数据解析
- (void)creatDataWith:(NSInteger)page{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:[NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/T1348647853363/%ld-20.html",self.page] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (self.isUpLoading == NO) {
            [self.array removeAllObjects];
            [self.headArray removeAllObjects];
        }
        NSArray *Array = [responseObject objectForKey:@"T1348647853363"];
        NSDictionary *dict = Array[0];
        NSArray *head = dict[@"ads"];
        for (NSDictionary *dic in head) {
            CWCHeadModel *model = [[CWCHeadModel alloc]initWithDic:dic];
            [self.headArray addObject:model];
            [model release];
        }
        [self creatView];
        for (NSDictionary *dic in Array) {
            if (dic[@"imgextra"] == nil) {
            CWCDataModel *model = [[CWCDataModel alloc]initWithDic:dic];
            [self.array addObject:model];
                [model release];
            }else{
                CWCDataModel *model = [[CWCDataModel alloc]initWithDic:dic];
                NSArray *imgArray = dic[@"imgextra"];
                NSDictionary *imgDic1 = imgArray[0];
                NSString *urlImage1 = imgDic1[@"imgsrc"];
                [model setValue:urlImage1 forKey:@"imgsrc1"];
                NSDictionary *imgDic2 = imgArray[1];
                NSString *urlImage2 = imgDic2[@"imgsrc"];
                [model setValue:urlImage2 forKey:@"imgsrc2"];
                [self.array addObject:model];
                [model release];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.hud hide:YES afterDelay:0];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView.mj_header endRefreshing];
        });
        [self.array removeObjectAtIndex:0];
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    

    
}
#pragma mark-视图创建
-(void)creatView{
    NSLog(@"%@", self.headArray );
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.tableHeaderView = self.headView;
    [self.tableView.mj_header beginRefreshing];
    [self.tableView registerClass:[CostomCell class] forCellReuseIdentifier:@"mycell"];
    [self.tableView registerClass:[CWCImageCell class] forCellReuseIdentifier:@"myCell"];
    
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH , 200)];
    self.headView.backgroundColor = [UIColor whiteColor];
    //[self.view addSubview:self.headView];
    self.tableView.tableHeaderView = self.headView;
    [self.headView release];
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    self.scrollView.contentSize = CGSizeMake(7 * WIDTH, 200);
    self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    [self.tableView addSubview:self.scrollView];
    self.scrollView.delegate = self;
    [self.scrollView release];
    self.btArray = [NSMutableArray array];
    for (NSInteger i = 0; i < self.headArray.count; i++) {
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH * (i + 1), 0, WIDTH , 200)];
        [self.scrollView addSubview:imgView];
        [imgView release];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5 + (WIDTH * (i + 1)), 175 , WIDTH * 2 / 3, 25)];
        [self.scrollView addSubview:titleLabel];
        [titleLabel release];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(WIDTH * (i + 1), 0, WIDTH, 200);
        button.backgroundColor = [UIColor clearColor];
        [self.scrollView addSubview:button];
        [button addTarget:self action:@selector(pushphotoDetailViewController:) forControlEvents:UIControlEventTouchUpInside];
        [self.btArray addObject:button];
        CWCHeadModel *model = self.headArray[i];
        [imgView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
        titleLabel.text = model.title;
        titleLabel.textColor = [UIColor whiteColor];
    }
    UIImageView *firstView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    [self.scrollView addSubview:firstView];
    UILabel *firstLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 175, WIDTH * 2 / 3, 25)];
    [self.scrollView addSubview:firstLabel];
    [firstView release];
    CWCHeadModel *lastModel = self.headArray[4];
    UIButton *firstButton = [UIButton buttonWithType:UIButtonTypeCustom];
    firstButton.frame = CGRectMake(0, 0, WIDTH, 200);
    firstButton.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:firstButton];
    [firstButton addTarget:self action:@selector(pushphotoDetailViewController:) forControlEvents:UIControlEventTouchUpInside];
    [self.btArray addObject:firstButton];
    [firstView sd_setImageWithURL:[NSURL URLWithString:lastModel.imgsrc]];
    firstLabel.text = lastModel.title;
    firstLabel.textColor = [UIColor whiteColor];
    
    UIImageView *lastView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH * 6, 0, WIDTH, 200)];
    [self.scrollView addSubview:lastView];
    [lastView release];
    UILabel *lastLabel = [[UILabel alloc]initWithFrame:CGRectMake((WIDTH * 6) + 5, 175, WIDTH / 2 * 3, 25)];
    [self.scrollView addSubview:lastLabel];
    [lastLabel release];
    UIButton *lastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    lastButton.frame = CGRectMake(WIDTH * 6, 0, WIDTH, 200);
    lastButton.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:lastButton];
    [lastButton addTarget:self action:@selector(pushphotoDetailViewController:) forControlEvents:UIControlEventTouchUpInside];
    [self.btArray addObject:lastButton];
    CWCHeadModel *firstModel = self.headArray[0];
    [lastView sd_setImageWithURL:[NSURL URLWithString:firstModel.imgsrc]];
    lastLabel.text = firstModel.title;
    lastLabel.textColor = [UIColor whiteColor];
    
    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(changeTimer) userInfo:nil repeats:YES];
    
    
    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(WIDTH * 2 / 3, 180, WIDTH / 3, 10)];
    self.pageControl.numberOfPages = 5;
    self.pageControl.pageIndicatorTintColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
    self.pageControl.currentPageIndicatorTintColor = AppColor ;
    [self.pageControl addTarget:self action:@selector(changeScrollViewOffset) forControlEvents:UIControlEventValueChanged];
    [self.headView addSubview:self.pageControl];
    [self.pageControl release];
   
}
-(void)pushphotoDetailViewController:(UIButton *)button{
    NSInteger index = [self.btArray indexOfObject:button];
    CWCPhotoDetailViewController *vc = [[CWCPhotoDetailViewController alloc]init];
    if (index == 0 || index == 5) {
        CWCHeadModel *model = self.headArray[0];
        NSString *str = [[model.url stringByReplacingOccurrencesOfString:@"|" withString:@"/"]substringFromIndex:4];
        vc.setid = str;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];

    }else if (index == 1 || index == 5){
        CWCHeadModel *model = self.headArray[1];
        NSString *str = [[model.url stringByReplacingOccurrencesOfString:@"|" withString:@"/"]substringFromIndex:4];
        vc.setid = str;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index == 2){
        CWCHeadModel *model = self.headArray[2];
        NSString *str = [[model.url stringByReplacingOccurrencesOfString:@"|" withString:@"/"]substringFromIndex:4];
        vc.setid = str;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index == 3){
        CWCHeadModel *model = self.headArray[3];
        NSString *str = [[model.url stringByReplacingOccurrencesOfString:@"|" withString:@"/"]substringFromIndex:4];
        vc.setid = str;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index == 4){
        CWCHeadModel *model = self.headArray[4];
        NSString *str = [[model.url stringByReplacingOccurrencesOfString:@"|" withString:@"/"]substringFromIndex:4];
        vc.setid = str;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)changeTimer{
    self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x + WIDTH, 0);
    [self scrollViewDidEndDecelerating:self.scrollView];
}

-(void)changeScrollViewOffset{
    NSInteger page = self.pageControl.currentPage;
    [self.scrollView setContentOffset:CGPointMake((page + 1) * WIDTH, 0) animated:YES];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x/scrollView.frame.size.width;
    NSInteger off_x = (int)scrollView.contentOffset.x%(int)scrollView.frame.size.width;
    if (page == 6 && off_x == 0) {  //恰好滚动到最后一张视图
        scrollView.contentOffset = CGPointMake(scrollView.frame.size.width, 0);
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x == 0) {
        self.scrollView.contentOffset = CGPointMake(WIDTH * 5, 0);
        self.pageControl.currentPage = 5;
    }else if (scrollView.contentOffset.x == WIDTH * 6){
        self.scrollView.contentOffset =CGPointMake(WIDTH , 0);
        self.pageControl.currentPage = 1;
    }else{
        NSInteger num = self.scrollView.contentOffset.x / WIDTH;
        self.pageControl.currentPage = num - 1;
    }
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CWCDataModel *model = self.array[indexPath.row];
    if (model.imgextra == nil) {
        CostomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycell"];
        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
        cell.titleLabel.text = model.title;
        cell.digestLabel.text = model.digest;
        cell.digestLabel.font = [UIFont systemFontOfSize:14];
        return cell;
    }else{
        CWCImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
        cell.titleLabel.text = model.title;
        cell.titleLabel.font = [ UIFont systemFontOfSize:16];
        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
        [cell.imgView1 sd_setImageWithURL:[NSURL URLWithString:model.imgsrc1]];
        [cell.imgView2 sd_setImageWithURL:[NSURL URLWithString:model.imgsrc2]];
        return cell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CWCDataModel *model = self.array[indexPath.row];
    if (!model.photosetID) {
        CWCNewsDetailViewController *vc = [[CWCNewsDetailViewController alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.id = model.docid;
        
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        CWCPhotoDetailViewController *vc = [[CWCPhotoDetailViewController alloc]init];
        vc.setid = model.photosetID;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }
}

-(void)dealloc{
    [_scrollView release];
    [_pageControl release];
    [_headView release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
